package com.zf.yichat.service.config;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zf.yichat.dto.ChatroomAdminUserDto;
import com.zf.yichat.dto.ChatroomMemberUserDto;
import com.zf.yichat.mapper.MessageChatroomAdminUserMapper;
import com.zf.yichat.mapper.MessageChatroomMapper;
import com.zf.yichat.mapper.UserJoinChatroomApplyMapper;
import com.zf.yichat.mapper.UserJoinChatroomMapper;
import com.zf.yichat.model.MessageChatroom;
import com.zf.yichat.model.MessageChatroomAdminUser;
import com.zf.yichat.model.UserJoinChatroom;
import com.zf.yichat.service.UserService;
import com.zf.yichat.utils.common.DateUtils;
import com.zf.yichat.utils.common.FsConst;
import com.zf.yichat.utils.common.N3d;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import io.rong.RongCloud;
import io.rong.methods.chatroom.Chatroom;
import io.rong.models.chatroom.ChatroomModel;
import io.rong.models.response.ChatroomUserQueryResult;
import io.rong.models.response.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author wu
 * 聊天室服务
 */
@Component
public class ChatroomService {

    // 注入配置文件中的融云API配置
    @Value("${rongcloud.key}")
    private String appKey;

    @Value("${rongcloud.secret}")
    private String appSecret;

    @Autowired
    private RongCloudApplication rongCloudApplication;


    public RongCloud rongCloud;

    @Autowired
    private MessageChatroomMapper messageChatroomMapper;

    @Autowired
    private MessageChatroomAdminUserMapper chatroomAdminUserMapper;

    @Autowired
    private UserJoinChatroomMapper userJoinChatroomMapper;

    @Autowired
    private UserJoinChatroomApplyMapper userJoinChatroomApplyMapper;

    @Autowired
    private UserService userService;

    public ChatroomService() {

    }

    // 添加聊天室
    @Transactional
    public Integer createChatroom(String name) throws Exception {

        // 创建聊天室
        String chatroomId = RandomUtil.randomNumbers(6);

        HttpPost httpPostCreate = rongCloudApplication.imConstructor("chatroom/create");
        List<NameValuePair> paramsCreate = new ArrayList<>();
        paramsCreate.add(new BasicNameValuePair("id", chatroomId));
        paramsCreate.add(new BasicNameValuePair("name", name));
        httpPostCreate.setEntity(new UrlEncodedFormEntity(paramsCreate, StandardCharsets.UTF_8));

        String responseCreate = rongCloudApplication.executeReq(httpPostCreate);
        // 解析响应数据
        JSONObject jsonObjectCreate = JSON.parseObject(responseCreate);
        String keepaliveCodeCreate = jsonObjectCreate.getString("code");

        if ("200".equals(keepaliveCodeCreate)) {
            // 保活已创建的聊天室
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/keepalive/add");

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("chatroomId", chatroomId));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
            String response = rongCloudApplication.executeReq(httpPost);

            // 解析响应数据
            JSONObject jsonObject = JSON.parseObject(response);
            String keepaliveCode = jsonObject.getString("code");
            // 保活聊天室成功后保存聊天室数据到数据库
            if ("200".equals(keepaliveCode)) {
                MessageChatroom messageChatroom = new MessageChatroom();
                messageChatroom.setChatroomId(chatroomId);
                messageChatroom.setChatroomName(name);
                messageChatroom.setCreateTime(new Date());
                messageChatroomMapper.insert(messageChatroom);
            }else {
                return FsConst.Status.EXCEED;
            }

        }
        // 处理 result 中的信息
        return 200;
    }


    // 查询所有聊天室
    public List<MessageChatroom> getChatroomList() throws Exception {
        // 存放存活的聊天室
        List<MessageChatroom> survival = new ArrayList<>();

        // 查询所有创建的聊天室
        List<MessageChatroom> chatroomList = messageChatroomMapper.selectAll();
        for (MessageChatroom messageChatroom : chatroomList) {
            Date createTime = messageChatroom.getCreateTime();
            DateUtils.formatDate(createTime);
            messageChatroom.setCreateTime(createTime);

//            // 看一下该聊天室是否存活（如 1 小时内该聊天室中没有发送过新消息或没有用户加入时，则该聊天室将自动销毁）
          String chatroomId = messageChatroom.getChatroomId();
//
//            // 查询保活的聊天室
//            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/keepalive/query");
//            String response = rongCloudApplication.executeReq(httpPost);

//            // 解析响应数据
//            JSONObject jsonObject = JSON.parseObject(response);
//            String keepaliveCode = jsonObject.getString("code");
//            String chatroomIds = jsonObject.getString("chatroomIds");
//            chatroomIds = chatroomIds.replaceAll ("\\[|\\]|\"", "");
//            List<String> chatroomIdList = Arrays.asList(chatroomIds.split(","));
//
//            if ("200".equals(keepaliveCode)) {
//                // 将融云服务器上存活的聊天室返回
//                if (chatroomIdList.contains(chatroomId)) {
                    survival.add(messageChatroom);
//                }
//            }
        }
        return survival;
    }

    public boolean chatroomDelete(String chatroomId) throws Exception{

        if (null == rongCloud) {
            rongCloud = RongCloud.getInstance(appKey, appSecret);
        }

        // 创建 Chatroom 实例并设置属性
        Chatroom chatroom = new Chatroom(appKey, appSecret, rongCloud);
        chatroom.setRongCloud(rongCloud);

        // 先查看聊天室是否存在
        ChatroomModel chatroomModel = new ChatroomModel();
        chatroomModel.setId(chatroomId);
        chatroomModel.setCount(Integer.MAX_VALUE);
        chatroomModel.setOrder(1);
        ChatroomUserQueryResult queryResult = chatroom.get(chatroomModel);
        if (200 == queryResult.getCode()) {
            ResponseResult responseResult = chatroom.destroy(chatroomModel);
            if (200 == responseResult.getCode()) {
                // 删除数据库中的数据
                messageChatroomMapper.deleteChatroomByChatroomId(chatroomId);
            }
            return true;
         }
        return false;
    }

    /**
     * 设置聊天室管理员
     * @param chatroomId 聊天室ID
     * @param userIds 要添加到白名单的人员
     * @return
     * @throws Exception
     */
    public Integer createChatroomAdmin(String chatroomId, String userIds) throws Exception {

        String[] split = userIds.split("\\|");

        // 添加到聊天室禁言白名单
        HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/user/ban/whitelist/add");

        // 设置请求消息体参数
        String encodeChatroomId = N3d.encode(Long.valueOf(chatroomId));
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("chatroomId", encodeChatroomId));

        for (String whiteId : split) {
            String encodeWhiteId = N3d.encode(Long.valueOf(whiteId));
            params.add(new BasicNameValuePair("userId", encodeWhiteId));
        }

        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

        String response = rongCloudApplication.executeReq(httpPost);
        // 解析响应数据
        JSONObject jsonObject = JSON.parseObject(response);
        String whitelistCode = jsonObject.getString("code");
        // 管理员设置成功后保存管理员与聊天室的数据到数据库
        if ("200".equals(whitelistCode)) {
            MessageChatroomAdminUser adminUser = new MessageChatroomAdminUser();
            adminUser.setChatroomId(chatroomId);
            for (int i = 0; i < split.length; i++) {
                String adminUserId = split[i];
                adminUser.setUserId(Long.valueOf(adminUserId));
                chatroomAdminUserMapper.insert(adminUser);


                // 查询在聊天室人员列表中是否存在该用户
                UserJoinChatroom chatroom = userJoinChatroomMapper.queryUserInChatroom(Long.valueOf(adminUserId), chatroomId);
                if(null == chatroom){
                    // 加入到群成员列表
                    UserJoinChatroom joinChatroom = new UserJoinChatroom();
                    joinChatroom.setUserId(Long.valueOf(adminUserId));
                    joinChatroom.setChatroomId(chatroomId);
                    joinChatroom.setCreateTime(new Date());
                    userJoinChatroomMapper.insert(joinChatroom);
                }

            }
            return FsConst.Status.IS_OK;
        }
        return FsConst.Status.EXCEED;
    }

    public List<MessageChatroomAdminUser> queryAdminListByChat(String chatroomId) {
        List<MessageChatroomAdminUser> list = chatroomAdminUserMapper.selectAdminListByChatId(chatroomId);
        return list;
    }

    @Transactional
    public FsResponse chatroomApply(String chatroomId, String userId, String status) {
       int i = userJoinChatroomApplyMapper.updateStatusByParam(chatroomId, userId, status);

       // 审核通过 新增聊天室成员信息
       if (UserJoinChatroom.STATUS_APPROVED.equals(status) && i > 0) {
           UserJoinChatroom chatroom = userJoinChatroomMapper.queryUserInChatroom(Long.valueOf(userId), chatroomId);
           if (null == chatroom) {

               if (!userService.realValidStatus(Long.valueOf(userId))) {
                   return FsResponseGen.failMsg("请先实名认证");
               }


               // 增加群成员信息
               UserJoinChatroom joinChatroom = new UserJoinChatroom();
               joinChatroom.setUserId(Long.valueOf(userId));
               joinChatroom.setChatroomId(chatroomId);
               joinChatroom.setCreateTime(new Date());
               return FsResponseGen.successData(userJoinChatroomMapper.insertSelective(joinChatroom));
           }
       }
        return FsResponseGen.successData(i);
    }

    public void chatroomUpdate(Long chatroomId, String status, String chatroomName) {
        if (StringUtils.isNotBlank(status)) {
            messageChatroomMapper.chatroomUpdateStatus(chatroomId, status);
        }
        else if (StringUtils.isNotBlank(chatroomName)) {
            messageChatroomMapper.chatroomUpdateChatroom(chatroomId, chatroomName);
        }
    }

    public List<ChatroomAdminUserDto> queryChatroomAdmin(String chatroomId, String userId, String nick, String mobile, String realName) {
        return chatroomAdminUserMapper.queryChatroomAdmin(chatroomId, userId, nick, mobile, realName);
    }

    public int deleteChatroomAdmin(String chatroomId, String userId) throws Exception {

        // 调取移除融云禁言白名单接口
        HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/user/ban/whitelist/rollback");

        // 设置请求消息体参数
        String encodeChatroomId = N3d.encode(Long.valueOf(chatroomId));
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("chatroomId", encodeChatroomId));

        String encodeWhiteId = N3d.encode(Long.valueOf(userId));
        params.add(new BasicNameValuePair("userId", encodeWhiteId));

        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
        String response = rongCloudApplication.executeReq(httpPost);
        // 解析响应数据
        JSONObject jsonObject = JSON.parseObject(response);
        String whitelistCode = jsonObject.getString("code");
        if ("200".equals(whitelistCode)) {
            // 删除本地数据库中的管理员信息
            return chatroomAdminUserMapper.deleteChatroomAdmin(chatroomId, userId);
        }
        return 0;
    }

    public List<ChatroomMemberUserDto> queryChatroomMember(String chatroomId, String userId, String nick, String mobile, String realName) {
        return userJoinChatroomMapper.queryChatroomMember(chatroomId, userId, nick, mobile, realName);
    }

    public int deleteChatroomMember(String chatroomId, String userId) {
        return userJoinChatroomMapper.deleteChatroomMember(chatroomId, userId);
    }

}
